package com.example.yk2021xm04.controller;


import com.example.yk2021xm04.model.RespBean;
import com.example.yk2021xm04.pojo.User;
import com.example.yk2021xm04.query.UserQuery;
import com.example.yk2021xm04.service.IUserService;
import com.example.yk2021xm04.utils.IDUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author ZengQi
 * @since 2021-11-26
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;

    /**
     * 用户管理主界面
     * @return
     */
    @RequestMapping("index")
    public String index() {
        return "user/user";
    }

    /**
     * 用户信息设置页面
     * @return
     */
    @RequestMapping("setting")
    public String setting(Model model){
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        model.addAttribute("user", user);
        return "user/setting";
    }


    /**
     * 用户信息更新
     * @param user
     * @return
     */
    @RequestMapping("updateUserInfo")
    @ResponseBody
    public RespBean updateUserInfo(User user){
        userService.updateUserInfo(user);
        return RespBean.success("用户信息更新成功");
    }


    /**
     * 用户密码更新页
     * @return
     */
    @RequestMapping("password")
    public String password(){
        return "user/password";
    }


    /**
     * 用户密码更新
     * @param principal
     * @param oldPassword
     * @param newPassword
     * @param confirmPassword
     * @return
     */
    @RequestMapping("updateUserPassword")
    @ResponseBody
    public RespBean updateUserPassword(Principal principal, String oldPassword, String newPassword, String confirmPassword) {
        userService.updateUserPassword(principal.getName(), oldPassword, newPassword, confirmPassword);
        return RespBean.success("用户密码更新成功");
    }

    /**
     * 添加更新用户页面
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("addOrUpdateUserPage")
    public String addOrUpdatePage(Integer id, Model model) {
        if (null!=id) {
            model.addAttribute("user",userService.getById(id));
        }
        return "user/add_update";
    }

    @RequestMapping("register")
    @ResponseBody
    public RespBean register(User user) {
        user.setActiveStatus(0);
        String activeCode = IDUtils.getUUID();
        user.setActiveCode(activeCode);
        userService.register(user);
        return RespBean.success("用户注册成功!请前往邮箱激活");
    }

    /**
     * 校验激活码
     * @param active_code
     * @return
     */
    @RequestMapping("checkCode")
    @ResponseBody
    public String checkCode(String active_code) {
        User user = userService.getUserByActiveCode(active_code);
        //如果用户不等于null，把用户状态修改status=1
        System.out.println(user);
        if (user != null) {
            user.setActiveStatus(1);
            //把code验证码清空，已经不需要了
            user.setActiveCode("");
            userService.updateUser(user);
            return "账号已激活";
        }
        return "激活失败";
    }

    @RequestMapping("list")
    @ResponseBody
    public Map<String, Object> userList(UserQuery userQuery) {
        return userService.userList(userQuery);
    }

    @RequestMapping("delete")
    @ResponseBody
    @PreAuthorize("hasAnyRole('超级管理员')")
    public RespBean deleteUser(Integer[] ids) {
        userService.deleteUser(ids);
        return RespBean.success("用户记录删除成功");
    }

    @RequestMapping("add")
    @ResponseBody
    @PreAuthorize("hasAnyRole('超级管理员')")
    public RespBean addUser(User user) {
        userService.addUser(user);
        return RespBean.success("用户记录添加成功");
    }


    @RequestMapping("update")
    @ResponseBody
    @PreAuthorize("hasAnyRole('超级管理员')")
    public RespBean updateUser(User user) {
        userService.updateUser(user);
        return RespBean.success("用户记录更新成功");
    }

    @RequestMapping("count")
    public String statistic() {
        return "user/user-statistics";
    }

    @RequestMapping("statistic")
    @ResponseBody
    public RespBean userStatistic() {
        //注册时间分组 group by day
        List<Object> registerTimeByDay = userService.registerTimeByDay();
        //一天中的注册用户数
        List<Object> registerCountByDay = userService.registerCountByDay();
        //日同比
        double rate = 0.0;
        //总用户数量
        Integer totalUserCount = userService.count();
        //今天的注册用户数量
        Integer UserCountInDay = userService.UserCountInDay();
        //昨天的注册用户数量
        Integer UserCountInYesterday = userService.UserCountInYesterday();

        rate = (double)(UserCountInDay - UserCountInYesterday) / UserCountInYesterday;
        if(UserCountInYesterday == 0) {
            rate = 0;
        }
        Map<String, Object> res = new HashMap<>();
        res.put("num", registerCountByDay);
        res.put("time", registerTimeByDay);
        res.put("total", totalUserCount);
        res.put("dayCount", UserCountInDay);
        res.put("rate", rate);
        return RespBean.success("用户统计数据返回成功",res);
    }

}
